{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Quantitative Trading"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This notebook is based on the learnings from [Quantitative Trading: How to build your own algorithm trading business](https://www.wiley.com/en-us/Quantitative+Trading%3A+How+to+Build+Your+Own+Algorithmic+Trading+Business-p-9780470284889). I am mostly interested in trading cryptocurrency (e.g. Bitcoin, Ethereum, and etc) therefore the index I will be focusing on will be the [cryptocurrency index](https://www.coingecko.com/en/crypto_index/crix). Below are some important concepts that will need to be considered with regards to algorithmic trading."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Strategies"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Information and Sharp ratio"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When considering strategies, one needs to consider one's goal... For myself I am interested in short-term (i.e. monthly income) gain. Based o nthe author of the QT text, long-term capital growth strategy of buy-and-hold one wouldn't necessarily be the best streategy for either long-term or short-term growth. In reality, the best strategy is the strategy that **maximizes Sharpe ratio**. So what is the Sharpe ratio (a.k.a. information ratio)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/latex": [
       "\\begin{align}\n",
       "\\text{Information Ratio} & = \\frac{\\text{Average of Excess Returns}}{\\text{SD of Excess Returns}} \\\\\n",
       "\\text{Excess Returns} & = \\text{Portfolio Returns} - \\text{Benchmark Returns}\n",
       "\\end{align}"
      ],
      "text/plain": [
       "<IPython.core.display.Latex object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "%%latex\n",
    "\\begin{align}\n",
    "\\text{Information Ratio} & = \\frac{\\text{Average of Excess Returns}}{\\text{SD of Excess Returns}} \\\\\n",
    "\\text{Excess Returns} & = \\text{Portfolio Returns} - \\text{Benchmark Returns}\n",
    "\\end{align}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The Benchmark Returns in this case would be the cryptocurrency index ([CRIX](http://crix.hu-berlin.de/)) whereas the Portfolio Returns would be based on the strategy one decides to employ."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The Sharp Ratio is a special case of Information Ratio when the strategy is dollar-neutral (i.e. the portfolio holds long and short positions with equal capital). An example of a dollar-neutral strategy would be when we have $50,000 capital, $25,000 for each long and short position would be held. In the case of using the Shapr Ratio, the Benchmark to use would be a risk-free rate. In practice, it is said that traders would use Sharp Ratio regardless of trading dollar-neutral (long and short equal capital) or directional (long or short only) strategy because it facilitaties comparison across different strategies. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Most strategies in industry quote the return rate not Sharp Ratio... This is poor practice because higher Sharp Ratio allows one to make more profits in the end by allowing trading at a higher leverage. This leveraged return is what matters most, not just the nominal return of the trading strategy."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Drawdowns"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Another important concept is drawdown. Based on the equity curve (which is based on the cumulative profit-and-loss curve), a drawdown is a decreased over time from peak to trough, while maximum drawdown would be a drawdawn that is greatest during the time period inspected and maximum drawdown duration would be the duration of a drawdown that is longest during the period inspected."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As a rule of thumb, a Sharp Ratio (henchforth SR) of 1 is not profitable whereas an annualized SR of 2 would be considered profitable every month. A SR of 3 would be considered profitable almost everyday. We would want a strategy that would have a SR greater than or equal to 3."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/latex": [
       "\\begin{align}\n",
       "\\text{Drawdown}(t) & = \\text{Current equity value} - \\text{Global maximum of the equity curve}(0,t_1) \\\\\n",
       "\\text{Maximum Drawdown} & = \\text{Global maximum of the equity curve}(0,t_1) - \\text{Global minimum of the curve}(t_2) \\ \\ \\text{for} \\ t_2 > t_1\n",
       "\\end{align}"
      ],
      "text/plain": [
       "<IPython.core.display.Latex object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "%%latex\n",
    "\\begin{align}\n",
    "\\text{Drawdown}(t) & = \\text{Current equity value} - \\text{Global maximum of the equity curve}(0,t_1) \\\\\n",
    "\\text{Maximum Drawdown} & = \\text{Global maximum of the equity curve}(0,t_1) - \\text{Global minimum of the curve}(t_2) \\ \\ \\text{for} \\ t_2 > t_1\n",
    "\\end{align}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Maximum Drawdown is a.k.a. \"high watermark\". Most often maximum dradown is represented as percentage terms. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/latex": [
       "\\begin{align}\n",
       "\\text{Drawdown}(t) & = \\frac{\\text{Loss of equity since reaching high watermark}}{\\text{Equity at high watermark}}\n",
       "\\end{align}"
      ],
      "text/plain": [
       "<IPython.core.display.Latex object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "%%latex\n",
    "\\begin{align}\n",
    "\\text{Drawdown}(t) & = \\frac{\\text{Loss of equity since reaching high watermark}}{\\text{Equity at high watermark}}\n",
    "\\end{align}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Our goal is to minimize drawdown. Plain and simple. One has to ask... How deep and how long can one tolerate the drawdown? 10% and 1 month? or 20% and 3 months? For me, I would say up to 40% and 3 months."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Transaction Costs"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Another Consideration is to determine how much transaction cost will affect the strategy. More transaction will lead to higher costs. The transaction costs are not just commission fees. There are other costs such as cost of liquidity (i.e. paying the bid-ask spread). If buying using limit orders, liquidity cost will be avoided but will incur opportunity costs because limit orders may not be exectued. Another concept *market impact* may be introduced as a large order may cause the prices of the stock even without having bought a single share."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Another potential cost that may result is due to *slippage*. Slippage occurs when there is a delay between the program transmitting the order and the brokerage executing the exchange due to internet or various software issues. This delay causes a difference in the price that triggers the order and the price when the execution happens. Usually the difference is negative (a cost) but it may be possible that the delay causes a positive difference. Deliberately delaying to allow for positive difference may be possible."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  Survivorship bias"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The idea of survivorship bias is when a historical database doesn't include stocks from companies that went bankrupt, delisted, M&A's. This causes bias because we are in essence only analyzing those companies that have done well therefore the sample that we are analyzing may not project future bankrupcies, delisting, and M&A's. An example of potential danger in analyzing historical data with survivorship bias is when a strategy tends to buy cheap stocks. The cheap stocks may be due to near bankruptcy of a company. If strategy is based only on those companies that have \"survived\" then the performance will indeed be good but will not be representative of the potential bankruptcy that may happen thus the projected outcome will be inflated. For example, a strategy that is used on backtest from periods further back compared to recent times may indicate long-only strategy would be better in early period of backtest than what the actual P&L would have at that time due ot the missing stocks from bankruptcy. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The term \"regimen shift\" needs to be considered. This basically is a concept that a strategy that would be a good fit from previous 10 years ago may not be a good strategy for today. Major changes in securities market regulation (such as decimalization of stock prices or eliminationo of short-sale rule) or other macroeconomic events (such as 08-09 sub-prime mortage crisis) may occur that may disrupt the previous model's implementation today. This idea in statistics basically translates to non-stationary process. Only if things before would carry over and have the same trend then would the process be stationary and we would be able to implement the same strategies 10 years before."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Data-snooping bias"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If we have many variables (e.g. 100) and try to fit the best model based on historical data, then it is likely that we will overfit the data and not have good predictions moving forward. The whole idea is to keep overfitting minimal and have a simple model that will do well over time."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Ernet Chan indicates that there are properties of AI that do well in financial prediction models:\n",
    "- AI based on sound econometric or rational basis do well compared to that of random discoery of patterns\n",
    "- Good prediction models only involve a few parameters\n",
    "- Only linear regression is used rather than some non-linear function\n",
    "- Conceptually simple\n",
    "- Optimization occurs in a lookback moving window, rather than involving unseen data."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Summary"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "These are a couple of my positions/stance on how this trading tip document will be operated:\n",
    "- Trading part-time\n",
    "- Programming so that automation occurs during the work-hours (when I will be doing my day job)\n",
    "- Initial capital of 10K (will start with virtual trading platform first)\n",
    "- Goal: Earn steady monthly income and also long-term capital gain"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Some tests to filter out bad strategies:\n",
    "- Does it outperform the benchmark? (Using information and/or Sharp ratio)\n",
    "- Is the drawdown small and drawdown duration short?\n",
    "- Does the backtest suffer from survivorship bias? (based on data that you gather)\n",
    "- Does trategy do poorly in recent years compared to earlier years (2k17 and 18 vs. early 2k's)\n",
    "- Does strategy have own nich that protects from competition from large hedge fund managers?"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
